package cn.com.anysdk.ocr.demo.controller;

import cn.com.anysdk.ocr.constant.OcrConstants.Language;
import cn.com.anysdk.ocr.model.OcrOptions;
import cn.com.anysdk.ocr.model.OcrResult;
import cn.com.anysdk.ocr.service.IOcrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/ocr")
public class OcrDemoController {

    @Autowired
    private IOcrService ocrService;

    @PostMapping(value = "/recognize", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public OcrResult recognizeImage(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "language", defaultValue = "CHINESE") Language language,
            @RequestParam(value = "detectOrientation", defaultValue = "true") boolean detectOrientation,
            @RequestParam(value = "returnConfidence", defaultValue = "true") boolean returnConfidence,
            @RequestParam(value = "returnBlock", defaultValue = "true") boolean returnBlock) throws IOException {

        OcrOptions options = OcrOptions.builder()
                .detectOrientation(detectOrientation)
                .language(language.toString())
                .timeout(10000)
                .preprocessOptions(OcrOptions.ImagePreprocessOptions.builder().build())
                .retryOptions(OcrOptions.RetryOptions.builder().build())
                .build();

        return ocrService.recognize(file.getInputStream(), options);
    }
}